<template>
    <div class="question-preview">
      <!-- 题目头部信息 -->
      <div class="question-header">
        <div class="question-meta">
          <el-tag type="primary">{{ getTypeText(question.questionType) }}</el-tag>
          <el-rate 
            :model-value="question.difficultyLevel" 
            disabled 
            show-score 
            text-color="#ff9900"
            score-template="{value}星"
          />
          <span class="points">{{ question.points }}分</span>
          <span class="time-limit">{{ question.timeLimit }}秒</span>
        </div>
        <div class="question-key">编号：{{ question.questionKey }}</div>
      </div>
  
      <!-- 题目标题 -->
      <div class="question-title">
        <h3>{{ question.questionTitle }}</h3>
      </div>
  
      <!-- 题目内容 -->
      <div class="question-content">
        <div v-html="question.questionContent"></div>
        <div v-if="question.questionImage" class="question-image">
          <el-image 
            :src="question.questionImage"
            fit="contain"
            style="max-width: 100%; max-height: 300px"
            :preview-src-list="[question.questionImage]"
          />
        </div>
      </div>
  
      <!-- 题目选项/答题区域 -->
      <div class="question-answer-area">
        <!-- 单选题 -->
        <div v-if="question.questionType === 'single_choice'" class="options-container">
          <div 
            v-for="option in getOptions()" 
            :key="option.key"
            class="option-item"
            :class="{ 'correct-option': isCorrectOption(option.key) }"
          >
            <el-radio 
              :model-value="previewAnswer"
              :value="option.key"
              @change="handleAnswerChange"
            >
              {{ option.key }}. {{ option.text }}
            </el-radio>
          </div>
        </div>
  
        <!-- 多选题 -->
        <div v-if="question.questionType === 'multiple_choice'" class="options-container">
          <div 
            v-for="option in getOptions()" 
            :key="option.key"
            class="option-item"
            :class="{ 'correct-option': isCorrectOption(option.key) }"
          >
            <el-checkbox 
              :model-value="previewAnswer"
              :value="option.key"
              @change="handleAnswerChange"
            >
              {{ option.key }}. {{ option.text }}
            </el-checkbox>
          </div>
        </div>
  
        <!-- 判断题 -->
        <div v-if="question.questionType === 'true_false'" class="options-container">
          <el-radio-group v-model="previewAnswer" @change="handleAnswerChange">
            <el-radio 
              :value="true"
              :class="{ 'correct-option': question.correctAnswer === true }"
            >
              正确
            </el-radio>
            <el-radio 
              :value="false"
              :class="{ 'correct-option': question.correctAnswer === false }"
            >
              错误
            </el-radio>
          </el-radio-group>
        </div>
  
        <!-- 填空题 -->
        <div v-if="question.questionType === 'fill_blank'" class="fill-blanks">
          <div 
            v-for="(blank, index) in getBlankAnswers()" 
            :key="index"
            class="blank-item"
          >
            <label>第{{ index + 1}}个空：</label>
            <el-input 
              v-model="previewAnswer[index]"
              placeholder="请输入答案"
              style="width: 200px; margin-left: 8px"
              @input="handleAnswerChange"
            />
            <span v-if="showAnswer" class="correct-answer">
              正确答案：{{ blank }}
            </span>
          </div>
        </div>
  
        <!-- 代码题 -->
        <div v-if="question.questionType === 'code'" class="code-area">
          <div class="code-info">
            <el-tag>{{ getLanguageText(question.programming_language) }}</el-tag>
          </div>
          <div class="code-template" v-if="question.code_template">
            <h4>代码模板：</h4>
            <pre><code>{{ question.code_template }}</code></pre>
          </div>
          <div class="code-editor">
            <h4>请编写代码：</h4>
            <el-input 
              v-model="previewAnswer"
              type="textarea"
              :rows="10"
              placeholder="请在此处编写代码"
              @input="handleAnswerChange"
            />
          </div>
        </div>
  
        <!-- 问答题 -->
        <div v-if="question.questionType === 'essay'" class="essay-area">
          <el-input 
            v-model="previewAnswer"
            type="textarea"
            :rows="6"
            placeholder="请输入你的答案"
            @input="handleAnswerChange"
          />
        </div>
  
        <!-- 其他题型占位 -->
        <div v-if="['drag_drop', 'match', 'sort', 'project', 'interactive'].includes(question.questionType)" class="other-types">
          <el-alert 
            :title="`${getTypeText(question.questionType)}预览功能开发中`"
            type="info"
            show-icon
            :closable="false"
          />
        </div>
      </div>
  
      <!-- 提示信息 -->
      <div v-if="question.hint" class="question-hint">
        <el-alert 
          :title="question.hint"
          type="info"
          show-icon
          :closable="false"
        >
          <template #title>
            <strong>提示：</strong>{{ question.hint }}
          </template>
        </el-alert>
      </div>
  
      <!-- 答案解析 -->
      <div v-if="showAnswer && question.answerAnalysis" class="answer-analysis">
        <el-card header="答案解析">
          <div v-html="question.answerAnalysis"></div>
        </el-card>
      </div>
  
      <!-- 正确答案显示 -->
      <div v-if="showAnswer" class="correct-answer-display">
        <el-card header="正确答案">
          <div class="answer-content">
            <template v-if="question.questionType === 'single_choice'">
              选择：{{ getCorrectAnswerText() }}
            </template>
            <template v-else-if="question.questionType === 'multiple_choice'">
              选择：{{ getCorrectAnswerText() }}
            </template>
            <template v-else-if="question.questionType === 'true_false'">
              {{ question.correctAnswer ? '正确' : '错误' }}
            </template>
            <template v-else-if="question.questionType === 'fill_blank'">
              <div v-for="(answer, index) in getBlankAnswers()" :key="index">
                第{{ index + 1 }}空：{{ answer }}
              </div>
            </template>
            <template v-else-if="question.questionType === 'code'">
              <pre><code>{{ question.correctAnswer }}</code></pre>
            </template>
            <template v-else>
              <div v-html="question.correctAnswer"></div>
            </template>
          </div>
        </el-card>
      </div>
  
      <!-- 标签信息 -->
      <div v-if="question.knowledgePoints?.length || question.skillTags?.length" class="question-tags">
        <el-card header="相关标签">
          <div v-if="question.knowledgePoints?.length" class="tag-group">
            <span class="tag-label">知识点：</span>
            <el-tag 
              v-for="tag in question.knowledgePoints" 
              :key="tag"
              type="success"
              style="margin-right: 8px"
            >
              {{ tag }}
            </el-tag>
          </div>
          <div v-if="question.skillTags?.length" class="tag-group">
            <span class="tag-label">技能：</span>
            <el-tag 
              v-for="tag in question.skillTags" 
              :key="tag"
              type="warning"
              style="margin-right: 8px"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-card>
      </div>
  
      <!-- 操作按钮 -->
      <div class="preview-actions">
        <el-button @click="toggleAnswer">
          {{ showAnswer ? '隐藏答案' : '显示答案' }}
        </el-button>
        <el-button @click="resetAnswer">重置答案</el-button>
        <el-button type="primary" @click="checkAnswer">检查答案</el-button>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  
  const props = defineProps({
    question: {
      type: Object,
      required: true
    },
    showAnswerByDefault: {
      type: Boolean,
      default: false
    }
  })
  
  // 响应式数据
  const showAnswer = ref(props.showAnswerByDefault)
  const previewAnswer = ref('')
  
  // 题目类型映射
  const questionTypeMap = {
    single_choice: '单选题',
    multiple_choice: '多选题',
    true_false: '判断题',
    fill_blank: '填空题',
    code: '代码题',
    essay: '问答题',
    drag_drop: '拖拽题',
    match: '匹配题',
    sort: '排序题',
    project: '项目题',
    interactive: '交互题'
  }
  
  // 编程语言映射
  const languageMap = {
    javascript: 'JavaScript',
    python: 'Python',
    java: 'Java',
    cpp: 'C++',
    csharp: 'C#',
    go: 'Go'
  }
  
  // 工具函数
  const getTypeText = (type) => questionTypeMap[type] || type
  const getLanguageText = (lang) => languageMap[lang] || lang
  
  // 获取选项列表
  const getOptions = () => {
    try {
      if (typeof props.question.correctAnswer === 'string') {
        const parsed = JSON.parse(props.question.correctAnswer)
        return parsed.options || []
      }
      return props.question.options || []
    } catch (e) {
      return []
    }
  }
  
  // 获取填空答案
  const getBlankAnswers = () => {
    try {
      if (typeof props.question.correctAnswer === 'string') {
        return JSON.parse(props.question.correctAnswer)
      }
      return Array.isArray(props.question.correctAnswer) ? props.question.correctAnswer : []
    } catch (e) {
      return []
    }
  }
  
  // 获取正确答案
  const getCorrectAnswer = () => {
    if (props.question.questionType === 'single_choice' || props.question.questionType === 'multiple_choice') {
      try {
        if (typeof props.question.correctAnswer === 'string') {
          const parsed = JSON.parse(props.question.correctAnswer)
          return parsed.answer
        }
      } catch (e) {
        // 如果解析失败，直接返回原值
      }
    }
    return props.question.correctAnswer
  }
  
  // 检查是否为正确选项
  const isCorrectOption = (optionKey) => {
    const correctAnswer = getCorrectAnswer()
    if (Array.isArray(correctAnswer)) {
      return correctAnswer.includes(optionKey)
    }
    return correctAnswer === optionKey
  }
  
  // 获取正确答案文本
  const getCorrectAnswerText = () => {
    const options = getOptions()
    const correctAnswer = getCorrectAnswer()
    
    if (Array.isArray(correctAnswer)) {
      return correctAnswer.map(key => {
        const option = options.find(opt => opt.key === key)
        return option ? `${key}.${option.text}` : key
      }).join(', ')
    } else {
      const option = options.find(opt => opt.key === correctAnswer)
      return option ? `${correctAnswer}.${option.text}` : correctAnswer
    }
  }
  
  // 初始化答案
  const initAnswer = () => {
    switch (props.question.questionType) {
      case 'single_choice':
        previewAnswer.value = ''
        break
      case 'multiple_choice':
        previewAnswer.value = []
        break
      case 'true_false':
        previewAnswer.value = null
        break
      case 'fill_blank':
        previewAnswer.value = new Array(getBlankAnswers().length).fill('')
        break
      default:
        previewAnswer.value = ''
    }
  }
  
  // 事件处理
  const handleAnswerChange = () => {
    // 答案变化时的处理逻辑
  }
  
  const toggleAnswer = () => {
    showAnswer.value = !showAnswer.value
  }
  
  const resetAnswer = () => {
    initAnswer()
    ElMessage.success('答案已重置')
  }
  
  const checkAnswer = () => {
    const correctAnswer = getCorrectAnswer()
    let isCorrect = false
    
    switch (props.question.questionType) {
      case 'single_choice':
      case 'true_false':
        isCorrect = previewAnswer.value === correctAnswer
        break
      case 'multiple_choice':
        isCorrect = Array.isArray(previewAnswer.value) && 
                   Array.isArray(correctAnswer) &&
                   previewAnswer.value.length === correctAnswer.length &&
                   previewAnswer.value.every(ans => correctAnswer.includes(ans))
        break
      case 'fill_blank':
        const correctBlanks = getBlankAnswers()
        isCorrect = Array.isArray(previewAnswer.value) &&
                   previewAnswer.value.length === correctBlanks.length &&
                   previewAnswer.value.every((ans, index) => 
                     ans.trim().toLowerCase() === correctBlanks[index].trim().toLowerCase()
                   )
        break
      default:
        // 对于主观题，只提示已提交
        ElMessage.info('答案已提交，需要人工评阅')
        return
    }
    
    if (isCorrect) {
      ElMessage.success('回答正确！')
    } else {
      ElMessage.error('回答不正确，请再试试')
    }
    
    showAnswer.value = true
  }
  
  // 监听题目变化
  watch(() => props.question, () => {
    initAnswer()
  }, { immediate: true })
  
  // 初始化
  initAnswer()
  </script>
  
  <style scoped>
  .question-preview {
    padding: 20px;
    background: #fff;
    border-radius: 8px;
  }
  
  .question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 6px;
  }
  
  .question-meta {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .question-meta .points,
  .question-meta .time-limit {
    font-size: 14px;
    color: #606266;
  }
  
  .question-key {
    font-size: 14px;
    color: #909399;
  }
  
  .question-title h3 {
    margin: 0 0 16px 0;
    color: #303133;
    font-weight: 600;
  }
  
  .question-content {
    margin-bottom: 24px;
    line-height: 1.6;
  }
  
  .question-image {
    margin-top: 16px;
    text-align: center;
  }
  
  .question-answer-area {
    margin-bottom: 24px;
  }
  
  .options-container {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
  }
  
  .option-item {
    margin-bottom: 12px;
    padding: 8px;
    border-radius: 4px;
    transition: all 0.3s;
  }
  
  .option-item:hover {
    background: #f0f0f0;
  }
  
  .option-item.correct-option {
    background: #f0f9ff;
    border: 1px solid #409eff;
  }
  
  .fill-blanks {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
  }
  
  .blank-item {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
  }
  
  .blank-item label {
    min-width: 80px;
    font-weight: 500;
  }
  
  .correct-answer {
    margin-left: 12px;
    color: #67c23a;
    font-size: 14px;
  }
  
  .code-area {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
  }
  
  .code-info {
    margin-bottom: 12px;
  }
  
  .code-template {
    margin-bottom: 16px;
  }
  
  .code-template h4,
  .code-editor h4 {
    margin: 0 0 8px 0;
    font-size: 14px;
    color: #606266;
  }
  
  .code-template pre {
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 0;
  }
  
  .essay-area {
    background: #fafafa;
    padding: 16px;
    border-radius: 6px;
  }
  
  .other-types {
    padding: 16px;
  }
  
  .question-hint {
    margin-bottom: 20px;
  }
  
  .answer-analysis,
  .correct-answer-display {
    margin-bottom: 20px;
  }
  
  .answer-content {
    background: #f0f9ff;
    padding: 12px;
    border-radius: 4px;
    border-left: 4px solid #409eff;
  }
  
  .answer-content pre {
    background: #f5f5f5;
    padding: 12px;
    border-radius: 4px;
    overflow-x: auto;
    margin: 8px 0 0 0;
  }
  
  .question-tags {
    margin-bottom: 20px;
  }
  
  .tag-group {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  
  .tag-label {
    min-width: 60px;
    font-weight: 500;
    color: #606266;
  }
  
  .preview-actions {
    text-align: center;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
  
  .preview-actions .el-button {
    margin: 0 8px;
  }
  
  :deep(.el-rate) {
    display: flex;
    align-items: center;
  }
  
  :deep(.el-rate__text) {
    margin-left: 8px;
  }
  
  :deep(.el-alert) {
    margin-bottom: 0;
  }
  
  :deep(.el-card__header) {
    background-color: #f8f9fa;
    font-weight: 600;
  }
  </style>